package top.kikt.book.core.handlers

import org.jsoup.nodes.Document
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.core.handlers.common.CommonBookHandler
import top.kikt.book.util.getUrl
import java.nio.charset.Charset

class Jjxinshu : BaseBookHandler(), CommonBookHandler {
    override val host: String
        get() = "www.jjxinshu.com"

    override fun forceCharset(): Charset {
        return Charset.forName("utf8")
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val chapterList = document.select("#chapter_list > li")

        return chapterList.mapIndexed { index, it ->
            val a = it.select("a")[0]
            val url = a.getUrl(menuUrl)
            val name = a.text()
            ChapterMetaEntity(name, index, url, a)
        }
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val doc = getUrlDocument(chapterMetaEntity.url)

        val contentNode = doc?.select(".content .text_row_txt")?.get(0)?.select("p") ?: return null

        val sb = StringBuilder()
        for (node in contentNode) {
            val dTags = node.select("d")

            val text = dTags.toList().sortedBy {
                it.attr("data-index").toInt()
            }.map {
                it.text()
            }.joinToString("") {
                it
            }

            if (text.isEmpty()) {
                continue
            }
            sb.append(text)
            sb.append("\n")
        }

        return chapterMetaEntity.toChapterMetaEntity(sb.toString())
    }
}